package view;

import dao.LokalDB_DAO;
import database.DataBase;
import interfaces.EventInterface;
import interfaces.FirmaInterface;
import interfaces.ListenerInterface;
import interfaces.OrdreInterface;
import interfaces.ServerInterface;
import interfaces.VareInterface;
import interfaces.VaregruppeInterface;
import java.awt.Dimension;
import java.rmi.ConnectException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.swing.JPanel;
import model.LocalVare;
import model.LokalVaregruppe;
import model.ServerListener;

public class Client extends javax.swing.JFrame {

    private ServerInterface server;
    private DataBase db;
    private boolean isLoggedInAtServer;
    private FirmaInterface firma;
    // forms
    private ArrayList<OrdreLinieForm> ordrelinier;
    private ArrayList<VareLinieForm> varelinier;
    private ArrayList<LokalVaregruppe> varegrupper;
    private ArrayList<LocalVare> varer;
    private String ordrevisning;
    private String varevisning;
    private ArrayList<VaregruppeInterface> ggVaregrupper;
    private String vareGruppe;
    private ArrayList<VareLinje_OpretOrdre> ggVarerForms;
    ArrayList<VareInterface> ggVarer;
    private ArrayList<VareLinje_OpretOrdre> kurv;

    public Client() {
        isLoggedInAtServer = false;
        ordrelinier = new ArrayList<>();
        varelinier = new ArrayList<>();
        varegrupper = new ArrayList<>();

        ggVarer = new ArrayList();
        kurv = new ArrayList<>();
        ggVarerForms = new ArrayList<>();
        ggVaregrupper = new ArrayList<>();

        varer = new ArrayList<>();
        ordrevisning = "alle";

        try {
            initComponents();
            jButton_hentVarer.setVisible(false);
            jLabel_vaelgVaregruppe.setVisible(false);
            jComboBox_ggVaregrupper.setVisible(false);
            jButton_tilfoejTilKurv.setVisible(false);
            jButton_sendOrdre.setVisible(false);
            jPanel_firmanavntop.setVisible(false);
            jPanel_firmaoplysninger.setEnabled(false);
            jButton_opdater_kurv.setVisible(false);
            jlabel_samletsum.setVisible(false);

            setSize(1300, 700);
            Context nameContext = new InitialContext();
            String url = "rmi://localhost:1099/server";
            server = (ServerInterface) nameContext.lookup(url);
            final ListenerInterface listener = new ServerListener(this);
            server.addListener(listener);
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("Shutting down...");
                        server.rollback();
                        server.removeListener(listener);
                    } catch (RemoteException ex) {
                        System.out.println(ex.getLocalizedMessage());
                    }
                }
            }));
        } catch (ConnectException ec) {
            jLabel_message.setText("RMI fejl i forbindelse! fix n gen start");
        } catch (Exception ex) {
            jLabel_message.setText("RMI fejl i forbindelse! fix n gen start");
            System.out.println(ex.getLocalizedMessage());
        }

        // database login - fast for alle clienter - firmaer
        db = DataBase.getInstance();
        db.login("root", "root");

        //    rebuildVGCombo();
        //  hentVarer();
        updateLokalvaregrupper();
        visSkaerm();

    }

//    private void rebuildVGCombo() {
//        try {
//            System.out.println("------------------- rebuild combo -------------- ");
//
//            if (jRadioButton_lokalt.isSelected()) {
//                LokalDB_DAO vd = new LokalDB_DAO();
//                varegrupper = vd.hentVaregrupper();
//                System.out.println("--------------------1");
//                System.out.println("varegrupper lokalt efter hentning ");
//                System.out.println("hmm " + varegrupper.size());
//                System.out.println("--------------------2");
//
//            } else {
//                varegrupper = server.getVaregrupper();
//            }
//
//            jComboBox_varegrupper.removeAllItems();
//            if (varegrupper != null && varegrupper.size() >= 0) {
//                System.out.println("fundet varegrupper " + varegrupper.size());
//                for (VaregruppeInterface vg : varegrupper) {
//                    jComboBox_varegrupper.addItem(vg.getVareGruppeNavn());
//                }
//
//            }
//
//        } catch (RemoteException ex) {
//            jLabel_message.setText("Ohh no RMI - server connection failed");
//        } catch (SQLException ex) {
//            jLabel_message.setText("Ohh no Lokal database connection failed");
//        }
//    }
    private void visSkaerm() {
        try {
            showScreen();
            repaint();
            revalidate();
        } catch (RemoteException ex) {
            jLabel_message.setText("Fejl i visning af skærm  " + ex.getLocalizedMessage());
            ex.printStackTrace();
        }
    }

    public void passEvent(EventInterface evt) {
        try {
            jLabel_message.setText(evt.getMessage() + "\n");
            repaint();
        } catch (RemoteException ex) {
            jLabel_message.setText(ex.getLocalizedMessage());
        }
    }

    public void updateGGvaregrupper() throws RemoteException {
        jComboBox_ggVaregrupper.removeAllItems();
        for (VaregruppeInterface vgif : ggVaregrupper) {
            jComboBox_ggVaregrupper.addItem(vgif.getVareGruppeNavn());
        }
    }

    public void updateLokalvaregrupper() {
        LokalDB_DAO dao = new LokalDB_DAO();
        varegrupper = dao.hentVaregrupper();
        jComboBox_varegrupper.removeAllItems();
        for (LokalVaregruppe vg : varegrupper) {
            jComboBox_varegrupper.addItem(vg.getVareGruppeNavn());
        }
    }

    public void updateVarer() throws RemoteException {
        ggVarer = server.hentVarer(firma.getFirmanavn(), vareGruppe.toString());
        ggVarerForms.clear();
        jPanel_GGvarer.removeAll();
        int y = 2;
        for (VareInterface vif : ggVarer) {
            JPanel panel = new VareLinje_OpretOrdre(vif, 0);
            ggVarerForms.add((VareLinje_OpretOrdre) panel);
            panel.setVisible(true);
            panel.setPreferredSize(new Dimension(380, 36));
            panel.setLocation(1, y);
            jPanel_GGvarer.add(panel);
            y = y + 36;
        }
        jPanel_GGvarer.setPreferredSize(new Dimension(430, 240 + y));
        jPanel_GGvarer.setSize(430, 240 + y);
        jPanel_GGvarer.repaint();
        jPanel_GGvarer.validate();
    }

    public void updateKurv() {
        jPanel_kurv.removeAll();
        int y = 2;
        for (VareLinje_OpretOrdre o : kurv) {
            o.setVisible(true);
            o.setPreferredSize(new Dimension(380, 36));
            o.setLocation(1, y);
            jPanel_kurv.add(o);
            y = y + 36;
        }
        jPanel_kurv.setPreferredSize(new Dimension(430, 240 + y));
        jPanel_kurv.setSize(430, 240 + y);
        jPanel_kurv.repaint();
        jPanel_kurv.validate();
    }

    public double getOrdreSum() {
        double sum = 0;
        for (VareLinje_OpretOrdre vare : kurv) {
            sum = sum + vare.getSum();

        }
        return sum;
    }

    public void updateLokalVarer() {
        varelinier.clear();
        jPanel_varer.removeAll();
        int y = 2;
        for (LocalVare lv : varer) {
            System.out.println("skriver vare " + lv.getVareNavn());
            JPanel panel = new VareLinieForm(this, lv);
            varelinier.add((VareLinieForm) panel);
            panel.setVisible(true);
            panel.setPreferredSize(new Dimension(380, 36));
            panel.setLocation(1, y);
            jPanel_varer.add(panel);
            y = y + 36;
        }
        jPanel_varer.setPreferredSize(new Dimension(430, 240 + y));
        jPanel_varer.setSize(430, 240 + y);
        jPanel_varer.repaint();
        jPanel_varer.validate();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup_varer = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jPanel_firmanavntop = new javax.swing.JPanel();
        jLabel_firmallabeltop = new javax.swing.JLabel();
        jPanel_serverlogin = new javax.swing.JPanel();
        jTextField_username = new javax.swing.JTextField();
        jTextField_pass = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jPanel_firmaoplysninger = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel_firmanavn = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel_balance = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel_username = new javax.swing.JLabel();
        jButton_betalt = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jPanel_messagepanel = new javax.swing.JPanel();
        jLabel_message = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jComboBox_varegrupper = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel_GGvarer = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel_kurv = new javax.swing.JPanel();
        jLabel_vaelgVaregruppe = new javax.swing.JLabel();
        jComboBox_ggVaregrupper = new javax.swing.JComboBox();
        jButton_tilfoejTilKurv = new javax.swing.JButton();
        jButton_sendOrdre = new javax.swing.JButton();
        jButton_hentVarer = new javax.swing.JButton();
        jlabel_samletsum = new javax.swing.JLabel();
        jButton_opdater_kurv = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jPanel_ordrer = new javax.swing.JPanel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jPanel_varer = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(1670, 700));
        getContentPane().setLayout(null);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setLayout(null);

        jPanel_firmanavntop.setLayout(null);

        jLabel_firmallabeltop.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel_firmallabeltop.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel_firmallabeltop.setText("firma");
        jPanel_firmanavntop.add(jLabel_firmallabeltop);
        jLabel_firmallabeltop.setBounds(30, 10, 640, 40);

        jPanel1.add(jPanel_firmanavntop);
        jPanel_firmanavntop.setBounds(0, 0, 1270, 50);

        jPanel_serverlogin.setBackground(new java.awt.Color(204, 204, 204));
        jPanel_serverlogin.setLayout(null);

        jTextField_username.setText("Brian Jorgensen");
        jPanel_serverlogin.add(jTextField_username);
        jTextField_username.setBounds(100, 20, 160, 22);

        jTextField_pass.setText("Ostehandler Næstved");
        jPanel_serverlogin.add(jTextField_pass);
        jTextField_pass.setBounds(410, 20, 160, 22);

        jButton1.setText("login");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel_serverlogin.add(jButton1);
        jButton1.setBounds(600, 20, 59, 25);

        jLabel7.setText("kodeord");
        jPanel_serverlogin.add(jLabel7);
        jLabel7.setBounds(290, 20, 80, 16);

        jLabel8.setText("Brugernavn");
        jPanel_serverlogin.add(jLabel8);
        jLabel8.setBounds(10, 20, 80, 16);

        jLabel1.setText("Grossist database login");
        jPanel_serverlogin.add(jLabel1);
        jLabel1.setBounds(10, 0, 160, 20);

        jPanel1.add(jPanel_serverlogin);
        jPanel_serverlogin.setBounds(0, 0, 1270, 50);

        jPanel_firmaoplysninger.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153)));
        jPanel_firmaoplysninger.setLayout(null);

        jLabel3.setText("Firma");
        jPanel_firmaoplysninger.add(jLabel3);
        jLabel3.setBounds(20, 10, 60, 16);
        jPanel_firmaoplysninger.add(jLabel_firmanavn);
        jLabel_firmanavn.setBounds(140, 10, 180, 20);

        jLabel5.setText("Konto balance");
        jPanel_firmaoplysninger.add(jLabel5);
        jLabel5.setBounds(20, 40, 80, 16);
        jPanel_firmaoplysninger.add(jLabel_balance);
        jLabel_balance.setBounds(140, 40, 130, 16);

        jLabel6.setText("Logget ind");
        jPanel_firmaoplysninger.add(jLabel6);
        jLabel6.setBounds(20, 60, 80, 16);
        jPanel_firmaoplysninger.add(jLabel_username);
        jLabel_username.setBounds(140, 60, 130, 16);

        jButton_betalt.setText("BETAL BALANCE");
        jButton_betalt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_betaltActionPerformed(evt);
            }
        });
        jPanel_firmaoplysninger.add(jButton_betalt);
        jButton_betalt.setBounds(20, 140, 150, 25);

        jPanel1.add(jPanel_firmaoplysninger);
        jPanel_firmaoplysninger.setBounds(880, 200, 360, 190);

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel4.setText("VARER/LAGER");
        jPanel1.add(jLabel4);
        jLabel4.setBounds(20, 400, 170, 30);

        jPanel_messagepanel.setBackground(new java.awt.Color(204, 153, 255));
        jPanel_messagepanel.setLayout(null);

        jLabel_message.setForeground(new java.awt.Color(255, 255, 255));
        jPanel_messagepanel.add(jLabel_message);
        jLabel_message.setBounds(20, 10, 670, 20);

        jPanel1.add(jPanel_messagepanel);
        jPanel_messagepanel.setBounds(0, 60, 1270, 30);

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jButton2.setText("START NY ORDRE");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2);
        jButton2.setBounds(430, 120, 260, 30);

        jButton3.setText("ALLE");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton3);
        jButton3.setBounds(20, 170, 80, 25);

        jButton4.setText("IKKE BETALT");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton4);
        jButton4.setBounds(110, 170, 130, 25);

        jButton5.setText("IKKE MODTAGET");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton5);
        jButton5.setBounds(253, 170, 150, 25);

        jComboBox_varegrupper.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox_varegrupperActionPerformed(evt);
            }
        });
        jPanel1.add(jComboBox_varegrupper);
        jComboBox_varegrupper.setBounds(140, 440, 170, 22);

        jLabel9.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel9.setText("ORDRER");
        jPanel1.add(jLabel9);
        jLabel9.setBounds(20, 116, 190, 30);

        jScrollPane1.setViewportView(jPanel_GGvarer);

        jPanel1.add(jScrollPane1);
        jScrollPane1.setBounds(440, 200, 420, 190);

        jScrollPane2.setViewportView(jPanel_kurv);

        jPanel1.add(jScrollPane2);
        jScrollPane2.setBounds(440, 470, 420, 180);

        jLabel_vaelgVaregruppe.setText("Vælg varegruppe");
        jPanel1.add(jLabel_vaelgVaregruppe);
        jLabel_vaelgVaregruppe.setBounds(440, 170, 130, 16);

        jComboBox_ggVaregrupper.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jPanel1.add(jComboBox_ggVaregrupper);
        jComboBox_ggVaregrupper.setBounds(570, 170, 180, 22);

        jButton_tilfoejTilKurv.setText("TILFØJ TIL KURV");
        jButton_tilfoejTilKurv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_tilfoejTilKurvActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_tilfoejTilKurv);
        jButton_tilfoejTilKurv.setBounds(713, 400, 150, 25);

        jButton_sendOrdre.setText("SEND ORDRE");
        jButton_sendOrdre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_sendOrdreActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_sendOrdre);
        jButton_sendOrdre.setBounds(710, 440, 150, 25);

        jButton_hentVarer.setText("HENT");
        jButton_hentVarer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_hentVarerActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_hentVarer);
        jButton_hentVarer.setBounds(763, 170, 100, 25);

        jlabel_samletsum.setText("Sum");
        jPanel1.add(jlabel_samletsum);
        jlabel_samletsum.setBounds(440, 440, 130, 20);

        jButton_opdater_kurv.setText("OPDATER KURV");
        jButton_opdater_kurv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_opdater_kurvActionPerformed(evt);
            }
        });
        jPanel1.add(jButton_opdater_kurv);
        jButton_opdater_kurv.setBounds(570, 440, 130, 25);

        jScrollPane3.setViewportView(jPanel_ordrer);

        jPanel1.add(jScrollPane3);
        jScrollPane3.setBounds(20, 200, 390, 190);

        jScrollPane4.setViewportView(jPanel_varer);

        jPanel1.add(jScrollPane4);
        jScrollPane4.setBounds(20, 470, 390, 180);

        jLabel2.setText("Vælg varegruppe");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(30, 440, 110, 16);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(10, 0, 1660, 840);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String username = jTextField_username.getText();
        String password = jTextField_pass.getText();

        if (!username.isEmpty() && !password.isEmpty()) {
            try {
                isLoggedInAtServer = server.login(username, password);
                System.out.println("is logged in at server? : " + isLoggedInAtServer);
                if (isLoggedInAtServer) {
                    firma = server.hentFirma(username);
                    System.out.println("firma " + firma + "   " + username);
                }
            } catch (RemoteException ex) {
                jLabel_message.setText("Brugernavn eller kodeord findes ikke i databasen");
            }
        }
        visSkaerm();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextField_usernameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_usernameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField_usernameActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        jLabel_message.setText("viser alle ordre");
        ordrevisning = "alle";
        visSkaerm();
        revalidate();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        jLabel_message.setText("ikke betalte ordre");
        ordrevisning = "ikkebetalte";
        visSkaerm();
        revalidate();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        jLabel_message.setText("Ikke modtagne ordre");
        ordrevisning = "ikkemodtagede";
        visSkaerm();
        revalidate();
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton_betaltActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_betaltActionPerformed
        jLabel_message.setText("så er der betalta");
        try {
            ArrayList<OrdreInterface> iv = server.hentIkkeBetalteOrdre(firma.getFirmanavn());
            if (iv != null) {
                for (OrdreInterface ordre : iv) {
                    System.out.println("ordre betales " + ordre.getOrdreID());
                    server.betalOrdre(ordre.getOrdreID(), firma.getFirmanavn());
                }
            }
        } catch (RemoteException ex) {
            jLabel_message.setText("FEJL i hentning af ikke betalte ordre");
        }
        visSkaerm();
        revalidate();

    }//GEN-LAST:event_jButton_betaltActionPerformed

    private void jComboBox_varegrupperActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_varegrupperActionPerformed

        LokalDB_DAO dao = new LokalDB_DAO();
        varer = dao.hentVare(jComboBox_varegrupper.getSelectedItem().toString());
        updateLokalVarer();

    }//GEN-LAST:event_jComboBox_varegrupperActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        jButton_hentVarer.setVisible(true);
        jLabel_vaelgVaregruppe.setVisible(true);
        jComboBox_ggVaregrupper.setVisible(true);
        jButton_tilfoejTilKurv.setVisible(true);
        jButton_sendOrdre.setVisible(true);
        jButton_opdater_kurv.setVisible(true);
        jlabel_samletsum.setVisible(true);
        try {
            ggVaregrupper = server.getVaregrupper();
            updateGGvaregrupper();
        } catch (RemoteException ex) {
            System.out.println(ex.getMessage());
        }

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton_tilfoejTilKurvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_tilfoejTilKurvActionPerformed

        jPanel_kurv.setVisible(true);
        ArrayList<VareLinje_OpretOrdre> temp = new ArrayList();
        temp.clear();
        for (VareLinje_OpretOrdre vare : ggVarerForms) {
            if (!vare.getAntal().getText().equals("0")) {
                temp.add(vare);
            }
        }
        for (VareLinje_OpretOrdre vare : temp) {
            System.out.println(temp.size());
            if (temp.size() > 1) {
                jLabel_message.setText("Bestil én vare af gangen...");
                return;
            } else {
                try {              
                    VareLinje_OpretOrdre v = new VareLinje_OpretOrdre(vare.getVif(), Integer.parseInt(vare.getAntal().getText()));
                    double samletPris = v.getVif().getVarePris() * Integer.parseInt(vare.getAntal().getText());
                    v.getPrisLabel().setText("Samlet pris: " + Double.toString(samletPris));
                    if (kurv.size() == 0) {
                        kurv.add(v);

                        System.out.println("---------------------------------------");
                        System.out.println("LÅSER DATABASEN!!!!");
                        System.out.println("---------------------------------------");
                        server.lockStart(vare.getVif().getVareNavn(), vare.getVif().getVareGruppe());

                        vare.setAntal(1);
                        jlabel_samletsum.setText("Samlet sum: " + getOrdreSum());
                        updateKurv();
                        updateVarer();
                        jLabel_message.setText("");
                    } else {
                        for (VareLinje_OpretOrdre vTest : kurv) {
                            if (v.getVif().getVareNavn().equals(vTest.getVif().getVareNavn())) {
                                jLabel_message.setText("Vare er allerede tilføjet til kurv... opdater antal...");
                                return;
                            } else {
                                kurv.add(v);
                                System.out.println("---------------------------------------");
                                System.out.println("LÅSER DATABASEN!!!!");
                                System.out.println("---------------------------------------");
                                server.lockStart(vare.getVif().getVareNavn(), vare.getVif().getVareGruppe());

                                vare.setAntal(0);
                                jlabel_samletsum.setText("Samlet sum: " + getOrdreSum());
                                updateKurv();
                                updateVarer();
                                jLabel_message.setText("");
                            }
                        }
                    } 
                } catch (RemoteException ex) {
                    jLabel_message.setText("fejl i remote connection rmi");
                }
            }
        }
        
    }//GEN-LAST:event_jButton_tilfoejTilKurvActionPerformed

    private void jButton_sendOrdreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_sendOrdreActionPerformed

        try {
            int ordreNr = server.opretOrdre(firma.getFirmanavn().toString());
            System.out.println("Onr: " + ordreNr);

            for (VareLinje_OpretOrdre vForm : kurv) {
                vForm.setAntal(Integer.parseInt(vForm.getAntal().getText()));
                if (Integer.parseInt(vForm.getAntal().getText()) > 0) {
                    server.tilføjVareTilOrdre(ordreNr, vForm.getVif().getVareNavn(), vForm.getVif().getVareGruppe(),
                            vForm.getVif().getVarePris(), Integer.parseInt(vForm.getAntal().getText()));

                    jButton_hentVarer.setVisible(false);
                    jLabel_vaelgVaregruppe.setVisible(false);
                    jComboBox_ggVaregrupper.setVisible(false);
                    jButton_tilfoejTilKurv.setVisible(false);
                    jButton_sendOrdre.setVisible(false);
                    jButton_opdater_kurv.setVisible(false);
                    jlabel_samletsum.setVisible(false);
                    jPanel_GGvarer.removeAll();
                    jPanel_kurv.removeAll();
                    jLabel_message.setText("viser alle ordre");
                    ordrevisning = "alle";
                    visSkaerm();
                    revalidate();
                }
            }
            kurv.clear();
            server.lockEnd();
        } catch (RemoteException ex) {
            System.out.println(ex.getMessage());
        }
    }//GEN-LAST:event_jButton_sendOrdreActionPerformed

    private void jButton_hentVarerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_hentVarerActionPerformed
        vareGruppe = jComboBox_ggVaregrupper.getSelectedItem().toString();
        try {
            updateVarer();
        } catch (RemoteException ex) {
            System.out.println(ex.getMessage());
        }
    }//GEN-LAST:event_jButton_hentVarerActionPerformed

    private void jButton_opdater_kurvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_opdater_kurvActionPerformed
        for (VareLinje_OpretOrdre vare : kurv) {
            int antal = Integer.parseInt(vare.getAntal().getText());
            vare.setAntal(antal);
            vare.setPris();
            jlabel_samletsum.setText("Samlet sum: " + getOrdreSum());
            updateKurv();
        }
    }//GEN-LAST:event_jButton_opdater_kurvActionPerformed

//    private void hentVarer() {
//        System.out.println("HENTER VARE!!!!");
//        int nummer = jComboBox_varegrupper.getSelectedIndex();
//        if (nummer < 0) {
//            nummer = 0;
//        }
//
//        System.out.println("nummer  " + nummer + "   " + jRadioButton_lokalt.isSelected() + "    gg  " + jRadioButton_gg.isSelected());
//        try {
//            if (jRadioButton_lokalt.isSelected()) {
//                System.out.println("i lokalt");
//                LokalDB_DAO vd = new LokalDB_DAO();
//                //if (varegrupper != null && nummer < varegrupper.size()) {
//                System.out.println("sætter varer");
//                varer = vd.hentVare(varegrupper.get(nummer).getVareGruppeNavn());
//                System.out.println("" + varer.size());
//                //}
//            } else {
//                System.out.println("gg varer");
//                //if (varegrupper != null && nummer < varegrupper.size()) {
//                System.out.println("sætter varer ");
//                varer = new ArrayList<>();
//                varer = server.rabatCheck(firma.getFirmanavn(), varegrupper.get(nummer).getVareGruppeNavn());
//                if (varer != null) {
//                    System.out.println("brian" + varer.size());
//                } else {
//                    System.out.println("virkerikke");
//                }
//
//                //}
//            }
//
//        } catch (RemoteException ex) {
//            jLabel_message.setText("Fejl i RMI under hentning af vare i varegrupper");
//        } catch (SQLException ex) {
//            jLabel_message.setText("Fejl i Lokal database under hentning af vare i varegrupper");
//        }
//
//    }
    public void showScreen() throws RemoteException {
        //  login skærm til serveren - rmi
        if (isLoggedInAtServer) {
            jPanel_serverlogin.setEnabled(false);
            jPanel_serverlogin.setVisible(false);

            jPanel_firmaoplysninger.setVisible(true);
            //    firma oplysninger bund af skærm
            if (firma != null) {
                try {
                    jLabel_firmanavn.setText(firma.getFirmanavn());
                    jLabel_username.setText(jTextField_username.getText());
                    jLabel_balance.setText("" + firma.getKonto());
                    jLabel_firmallabeltop.setText("" + firma.getFirmanavn().toUpperCase());
                    jPanel_firmanavntop.setVisible(true);
                    jPanel_firmaoplysninger.setEnabled(true);
                } catch (RemoteException ex) {
                    System.out.println("Server forbindelse FEJL");
                }

                //     show ordre liste
                ArrayList<OrdreInterface> alleordre;

                switch (ordrevisning) {
                    case "ikkebetalte":
                        alleordre = server.hentIkkeBetalteOrdre("" + firma.getFirmanavn());
                        break;
                    case "ikkemodtagede":
                        alleordre = server.ikkeModtagedeOrdre("" + firma.getFirmanavn());
                        break;
                    default:
                        alleordre = server.hentAlleOrdre("" + firma.getFirmanavn());
                        System.out.println("vælger alle ");
                        break;
                }

                if (alleordre != null) {
                    ordrelinier.clear();
                    jPanel_ordrer.removeAll();
                    System.out.println("------------------- VIS ORDRE ----------------------");
                    System.out.println("størrelse " + alleordre.size() + "  ");

                    int y = 5;

                    for (OrdreInterface ordre : alleordre) {
                        OrdreLinieForm panel = new OrdreLinieForm(this, ordre.getOrdreID(), ordre.isBetalt(), ordre.isModtaget(), ordre.getSum());
                        ordrelinier.add(panel);
                        panel.setVisible(true);
                        panel.setPreferredSize(new Dimension(389, 28));
                        panel.setLocation(5, y);
                        jPanel_ordrer.add(panel);
                        y = y + 28;
                    }
                    jPanel_ordrer.setPreferredSize(new Dimension(400, 100 + y));
                    jPanel_ordrer.setSize(390, 100 + y);
                }

                //      VARER
                //    show vare liste
                //  varer items
//                if (varer != null) {
//                    varelinier.clear();
//                    jPanel_varer.removeAll();
//
//                    System.out.println("------------------- VIS VARER ----------------------");
//
//                    System.out.println("er inde i varer " + varer.size() + "  ");
//
//                    int y = 5;
//
////                    for (VareInterface vare : varer) {
////                        VareLinieForm panel = new VareLinieForm(this, vare.getVareNavn(), vare.getVarePris(), vare.getAntal(), vare.getVareGruppe());
////                        varelinier.add(panel);
////                        panel.setVisible(true);
////                        panel.setPreferredSize(new Dimension(389, 28));
////                        panel.setLocation(5, y);
////                        jPanel_varer.add(panel);
////                        y = y + 28;
////                    }
//                    jPanel_varer.setPreferredSize(new Dimension(400, 100 + y));
//                    jPanel_varer.setSize(390, 100 + y);
//                } else {
//                    System.out.println("vare findes ikke");
//                }

            }

        } else {
            jPanel_firmaoplysninger.setVisible(false);
            jPanel_serverlogin.setEnabled(true);
            jPanel_serverlogin.setVisible(true);
        }
        System.out.println("------------------- FÆRDIG VIS  ----------------------");
    }

    protected void setOrdreTilAtVaereModtaget(int ordreid) {
        try {
            server.ordreModtaget(ordreid, firma.getFirmanavn());

            OrdreInterface ordre = server.hentFuldOrdre(firma.getFirmanavn(), ordreid);

            LokalDB_DAO dao = new LokalDB_DAO();
            dao.updateOrdre(ordre);

            if (isLoggedInAtServer) {
                String username = jTextField_username.getText();
                firma = server.hentFirma(username);
            }
            updateLokalVarer();
            visSkaerm();
        } catch (RemoteException ex) {
            System.out.println("fejl i at fortælle man har modtaget ordre " + ordreid);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Client().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup_varer;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton_betalt;
    private javax.swing.JButton jButton_hentVarer;
    private javax.swing.JButton jButton_opdater_kurv;
    private javax.swing.JButton jButton_sendOrdre;
    private javax.swing.JButton jButton_tilfoejTilKurv;
    private javax.swing.JComboBox jComboBox_ggVaregrupper;
    private javax.swing.JComboBox jComboBox_varegrupper;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLabel jLabel_balance;
    private javax.swing.JLabel jLabel_firmallabeltop;
    private javax.swing.JLabel jLabel_firmanavn;
    private javax.swing.JLabel jLabel_message;
    private javax.swing.JLabel jLabel_username;
    private javax.swing.JLabel jLabel_vaelgVaregruppe;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel_GGvarer;
    private javax.swing.JPanel jPanel_firmanavntop;
    private javax.swing.JPanel jPanel_firmaoplysninger;
    private javax.swing.JPanel jPanel_kurv;
    private javax.swing.JPanel jPanel_messagepanel;
    private javax.swing.JPanel jPanel_ordrer;
    private javax.swing.JPanel jPanel_serverlogin;
    private javax.swing.JPanel jPanel_varer;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextField jTextField_pass;
    private javax.swing.JTextField jTextField_username;
    private javax.swing.JLabel jlabel_samletsum;
    // End of variables declaration//GEN-END:variables
}
